import { createRouter, createWebHistory } from 'vue-router';
import Login from './views/Login.vue';
import UserDashboard from './views/UserDashboard.vue';
import ManagerDashboard from './views/ManagerDashboard.vue';
import Article from './views/Article.vue';
import Profile from './views/Profile.vue';
import Chat from './views/Chat.vue'; 

const routes = [
  {
    path: '/',
    name: 'login',
    component: Login
  },
  {
    path: '/user-dashboard',
    name: 'user-dashboard',
    component: UserDashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/manager-dashboard',
    name: 'manager-dashboard',
    component: ManagerDashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/article',
    name: 'article',
    component: Article,
    meta: { requiresAuth: true },
    props: true
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile,
    meta: { requiresAuth: true }
  },
  {
    path: '/chat',
    name: 'chat',
    component: Chat,
    meta: { requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_API_BASE_URL || '/'),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  
  if (to.meta.requiresAuth && !token) {
    next('/');
  } else if (to.path === '/' && token) {
    const loginType = localStorage.getItem('loginType') || 'user';
    const route = loginType === 'user' ? '/user-dashboard' : '/manager-dashboard';
    next(route);
  } else {
    next();
  }
});

export default router;